import { ProTable, ProTableProps } from '@ant-design/pro-components';
import { useLocation } from '@umijs/max';
import type { TableColumnsType } from 'antd';
import React, { useEffect, useRef } from 'react';
import type { ResizeCallbackData } from 'react-resizable';
import { Resizable } from 'react-resizable';
import styles from './style.less';

const ResizableTitle = (
  props: React.HTMLAttributes<any> & {
    onResize: (
      e: React.SyntheticEvent<Element>,
      data: ResizeCallbackData,
    ) => void;
    width: number;
  },
) => {
  const { onResize, width, ...restProps } = props;
  // console.log(width, restProps.children[1].props.label);
  if (!width) {
    return <th {...restProps} />;
  }
  return (
    <Resizable
      width={width}
      height={0}
      handle={
        <span
          className={styles.resizable}
          onClick={(e) => {
            e.stopPropagation();
          }}
        />
      }
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} style={{ ...restProps?.style, userSelect: 'none' }} />
    </Resizable>
  );
};
let myColumns: any[] = [];
const ResizableTable = (props: ProTableProps<any, any, any>) => {
  const { columns } = props;
  const [resizeColumns, setResizeColumns] = React.useState<any[]>([]);
  const { pathname } = useLocation();
  const elementRef = useRef<HTMLDivElement>(null);
  const storage_name = 'resize_table_' + pathname;

  useEffect(() => {
    if (!columns) {
      return;
    }
    // 将存储中的自定义宽度信息取出来
    const column_width = localStorage.getItem(storage_name);
    myColumns = columns.map((v) => {
      return {
        ...v,
        width: v.width,
      };
    });
    if (column_width) {
      const arr: any[] = JSON.parse(column_width);
      arr.forEach((v: any, k: number) => {
        if (myColumns[k]) {
          myColumns[k].width = v.width;
        }
      });
    }
    setResizeColumns(myColumns);
  }, [columns, pathname]);

  type ResizeFunction = (
    index: number,
  ) => (_: React.SyntheticEvent<Element>, data: ResizeCallbackData) => void;
  // 设置字段&页面存储
  const handleResize: ResizeFunction =
    (index: number) =>
    (_: React.SyntheticEvent<Element>, { size }: ResizeCallbackData) => {
      if (columns) {
        myColumns[index] = {
          ...myColumns[index],
          width: size.width,
        };
        const str = JSON.stringify(myColumns.map((v) => ({ width: v.width })));
        localStorage.setItem(storage_name, str);
        setResizeColumns([...myColumns]);
        // console.log(elementRef.current?.getElementsByClassName("ant-table-content"));;
        // console.log(index);
        // console.log(elementRef.current?.getElementsByTagName("colgroup")[0].childNodes);
        // const nodes = elementRef.current?.getElementsByTagName("colgroup")[0].childNodes;
        // if (nodes) {
        //   nodes[index+1].style.width = size.width + 'px';
        // }
        // console.log(size.width)
      }
    };

  const mergedColumns = resizeColumns.map<TableColumnsType<any>[number]>(
    (col, index) => {
      return {
        ...col,
        onHeaderCell: (column: TableColumnsType<any>[number]) => ({
          width: column.width,
          onResize: handleResize(index) as React.ReactEventHandler<any>,
        }),
      };
    },
  );

  return (
    <div ref={elementRef}>
      <ProTable
        search={false}
        options={false}
        tableAlertRender={false}
        columnEmptyText={false}
        {...props}
        bordered
        components={{
          header: {
            cell: ResizableTitle,
          },
        }}
        //@ts-ignore
        columns={mergedColumns}
      />
    </div>
  );
};

export default ResizableTable;
